package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ArticleHomeMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleHomeService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lzq
 * @data 2023/4/27 19:45
 */
@Service
public class ArticleHomeServiceImpl extends ServiceImpl<ArticleHomeMapper, ApArticle> implements ArticleHomeService {

    //点赞
    public static final String LIKES_BEHAVIOR="likes.Behavior";
    //喜欢不喜欢
    public static final String UN_LIKE_BEHAVIOR="un.likes.behavior";
    //收藏
    public static final String COLLECTION_BEHAVIOR ="collection.behavior";
    //我的关注
    public static final String APUSER_FOLLOW_RELATION="apUser.follow.relation";


    @Autowired
    private ArticleHomeMapper homeMapper;
    //单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    public ResponseResult load(ArticleHomeDto dto, Short type) {
        //1.校验参数
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        size = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(size);

        //类型参数检验
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        //查询数据
        List<ApArticle> apArticles = homeMapper.loadArticleList(dto, type);
        //返回
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 首页文章加载
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult loadFastPage(ArticleHomeDto dto, Short type) {
        //参数校验
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取缓存中数据
        String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if (jsonStr!=null){
            //返回频道对应热点文章
            List<ApArticle> apArticles = JSONArray.parseArray(jsonStr, ApArticle.class);
            return ResponseResult.okResult(apArticles);
        }
        //如果缓存没有数据,返回数据数据(非热点排名)
        return  load(dto,type);

    }


    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    /**
     * 保存app端相关文章
     * @param dto
     * @return
     */
    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //2.判断是否存在id
        if (dto.getId() == null) {
            //2.1 不存在id  保存  文章  文章配置  文章内容

            //保存文章
            save(apArticle);

            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //保存 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else {
            //2.2 存在id   修改  文章  文章内容

            //修改  文章
            updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //异步调用生成html文件
        articleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());
        //3.结果返回  文章的id
        return ResponseResult.okResult(apArticle.getId());
        //编写postman测试!!!!!
    }

    /**
     * 回显文章行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //是否关注
         boolean isfollow = false;
         //是否点赞
         boolean islike = false;
         //是否喜欢
         boolean isunlike = false;
         //是否收藏
         boolean iscollection = false;
        //数据校验
        if (dto.getArticleId()==null||dto.getAuthorId()==null||dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断你是否点赞
        String likeJsonStr = (String) cacheService.hGet(LIKES_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
        if (StringUtils.isNotBlank(likeJsonStr)){
            islike=true;
        }
        //判断是否不喜欢
        String unLikeJsonStr = (String) cacheService.hGet(UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
        if (StringUtils.isNotBlank(unLikeJsonStr)){
            isunlike=true;
        }
        //判断是否收藏
        String jsonDtoStr = (String) cacheService.hGet(COLLECTION_BEHAVIOR + user.getId().toString(), dto.getArticleId().toString());
        if (StringUtils.isNotBlank(jsonDtoStr)){
            iscollection=true;
        }
        //判断是否关注(判断是否有分数)
        Double score = cacheService.zScore(APUSER_FOLLOW_RELATION + user.getId().toString(), dto.getAuthorId().toString());
        if(score!=null){
            isfollow=true;
        }
        //封装数据返回
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("islike",islike);
        map.put("isunlike",isunlike);
        map.put("iscollection",iscollection);
        map.put("isfollow",isfollow);
        return ResponseResult.okResult(map);
    }


    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //获取之前五天的分数
        ApArticle oldArticle = getById(mess.getArticleId());
        Integer oldScore = computeOldScore(oldArticle);
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        //获取文章今天的分数三倍权重
        Integer newScore = computeNewScore(mess);
        Integer score = newScore +oldScore;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }



    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));

        }
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null?mess.getCollect():apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?mess.getComment():apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?mess.getLike():apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?mess.getView():apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;

    }

    /**
     * 计算文章的文章之前五天分值
     * @param apArticle
     * @return
     */
    private Integer computeOldScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.ARTICLE_LIKES;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.ARTICLE_COMMENT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.ARTICLE_COLLECTION;
        }

        return score;
    }
    //获取文章新的分数
    private Integer computeNewScore(ArticleVisitStreamMess mess) {
        Integer score = 0;

        score += mess.getLike() * ArticleConstants.ARTICLE_LIKES;
        score += mess.getView();
        score += mess.getComment() * ArticleConstants.ARTICLE_COMMENT;
        score += mess.getCollect() * ArticleConstants.ARTICLE_COLLECTION;

        return score*3;
    }
}
